/*
 * Copyright (c) 2017, Li Bo/Alex All rights reserved.
 * 
 * http://blog.sina.com.cn/alex4java
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package net.alex.jetty.server;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;

import net.alex.jetty.bean.JettyRunConfigure;
import net.alex.jetty.error.JettyServerError;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.xml.XmlConfiguration;

/**
 * @ClassName: InheritedJettyServer
 * @Description: 内嵌入方式的Jetty服务器组件<br>
 * 				   此方法功能类似于JettyServerRunner<br>
 * 				  有着同样的作用用于启动服务之后需要进行<br>
 * 				  此处采用的继承于org.eclipse.jetty.server.Server<br>
 * 				  类执行启动Jetty中间件进行热部署+加载项目对应的资源ROA	
 * @author: 李博/Alex
 * @date: 2017-2-24 上午10:09:19
 * @email:  alexlibochn@china-pui.com.cn
 */
public final class JettyServer extends Server {
	
	/**************系统默认端口：8080 缺省参数******************/
	private static final Integer DEFAULT_SERVER_PORT = 8080;
	
	/**************系统默认上下文路径：/ 缺省参数******************/
	private static final String DEFAULT_CONTEXT_PATH = "";

	/**************系统默认Jetty服务加载容器文件：默认当前路径下：./jetty/etc/webdefault.xml 缺省参数******************/
	private static final String DEFAULT_DESCRIPTOR = "jetty/etc/webdefault.xml";

	/**************系统默认Jetty服务加载Web资源文件：默认当前路径下：./WebRoot 缺省参数******************/
	private static final String DEFAULT_RESOURCE_BASE = "./WebRoot";
	
	/**************系统默认./etc/jetty.xml文件的路径：jetty.xml文件的路径 缺省参数******************/
	private static final String DEFAULT_JETTY_XML_PATH = "./etc/jetty.xml";
	
	/**
	 * @fieldName: configure
	 * @fieldType: JettyRunConfigure
	 * @Description: 总体JettyRun运行参数配置
	 */
	private JettyRunConfigure configure;

	/**
	 * @fieldName: JettyXmlPath
	 * @fieldType: String
	 * @Description: jetty.xml配置文件
	 */
	private String jettyXmlPath;
	
	/**
	 * @Title:InheritedJettyServer
	 * @Description:构造方法
	 * @param configure
	 */
	public JettyServer(JettyRunConfigure configure) {
		super();
		if(this.jettyXmlPath == null)
			this.configure = configure;
	}

	/**
	 * @Title:InheritedJettyServer
	 * @Description:构造方法
	 * @param jettyXmlPath
	 */
	public JettyServer(String jettyXmlPath) {
		super();
		if(this.configure == null)
			this.jettyXmlPath = jettyXmlPath;
	}
	
	public JettyRunConfigure getConfigure() {
		return configure;
	}

	public void setConfigure(JettyRunConfigure configure) {
		this.configure = configure;
	}

	public String getJettyXmlPath() {
		return jettyXmlPath;
	}

	public void setJettyXmlPath(String jettyXmlPath) {
		this.jettyXmlPath = jettyXmlPath;
	}

	/**
	 * @Title: startServer
	 * @Description: 启动Server服务器
	 * @return
	 * @return: boolean
	 */
	public synchronized boolean startServer(){
		try {
			loadWebAppHandler();
			super.start();
			super.join();
		} catch (Exception e) {
			if(!super.isStarted() &&  !super.isStarting()){
				try {
					super.start();
				} catch (Exception e1) {
					e1.printStackTrace();
					throw new JettyServerError("启动Server操作-->启动Server失败!",e1);
				}
			}
			throw new JettyServerError("启动Server操作-->启动Server失败!",e);
		}
		return false;
	}
	
	/**
	 * @Title: stopServer
	 * @Description: 关闭Server服务器
	 * @return
	 * @return: boolean
	 */
	public synchronized boolean stopServer(){
		try {
			super.stop();
		} catch (Exception e) {
			if(super.isStarted() || super.isStarting()){
				try {
					super.stop();
				} catch (Exception e1) {
					e1.printStackTrace();
					throw new JettyServerError("关闭Server操作-->二层关闭Server失败!",e1);
				}
			}
			throw new JettyServerError("关闭Server操作-->一层关闭Server失败!",e);
		}
		return false;
	}
	
	
	/**
	 * @Title: loadWebAppHandler
	 * @Description: 加载所有系统基本信息操作
	 * @throws Exception
	 * @return: void
	 */
	public synchronized void loadWebAppHandler() throws Exception{
		
		if(this.configure != null && this.jettyXmlPath != null)
			throw new JettyServerError("JettyRunConfigure对象与jettyXmlPath只能运行有一个进行配置服务!");
		else if(this.jettyXmlPath != null)
		{
			File file = new File(this.jettyXmlPath);
			if(file.exists())
			{
				XmlConfiguration configuration = new XmlConfiguration(new FileInputStream(file));
				configuration.configure(this);
			}
			else
			{
				URL url = Thread.currentThread().getContextClassLoader().getResource(this.jettyXmlPath);
				file = new File(url.getFile());
				if(file.exists())
				{
					XmlConfiguration configuration = new XmlConfiguration(url);
					configuration.configure(this);
				}
			}
		}
		else if(this.configure != null)
		{
			ContextHandlerCollection handler = new ContextHandlerCollection();
			WebAppContext context = new WebAppContext();
			context.setContextPath(this.configure.getContextPath() == null?this.DEFAULT_CONTEXT_PATH:this.configure.getContextPath());
			//context.setDefaultsDescriptor(this.configure.getDefaultsDescriptor() == null ? this.DEFAULT_DESCRIPTOR:this.configure.getDefaultsDescriptor());
			if(this.configure.getWarPath() != null)
			{
				context.setWar(this.configure.getWarPath());
			}
			else
			{
				context.setResourceBase(this.configure.getDeployResourceBasePath());
			}
			handler.addHandler(context);
			super.setHandler(handler);
		}
		else 
		{
			throw new JettyServerError("JettyRunConfigure对象与jettyXmlPath至少有一个进行初始化系统!");
		}
	}
	
	
	
	
}
